<script setup lang="ts">
import { ref } from "vue";
import type { ContractData } from "@/types/contract.types";
import { useSymbolSearch, MDominantIcon } from "./useSymbolSelector";
import { useListKeyboardNav } from "./useListKeyboardNav";

defineOptions({ name: "SymbolSearchDialogBody" });

const props = defineProps<{
  symbol?: string;
  showDetails?: boolean;
  onSelect: (c: ContractData) => void;
}>();

const emit = defineEmits<{ (e: "close", args?: any): void }>();

const { query, loading, results } = useSymbolSearch({
  initialQuery: props.symbol
});

const inputRef = ref<any>(null);

function handleSelect(item: ContractData) {
  props.onSelect(item);
  emit("close", { command: "sure" });
}

const { setItemRef, setContainerRef, onInputKeydown, onListKeydown } =
  useListKeyboardNav<ContractData>({
    items: results,
    onSelect: handleSelect,
    onEscapeFocus: () => {
      inputRef.value?.focus?.();
    }
  });

function onInputEnter(e: KeyboardEvent) {
  onInputKeydown(e);
}
</script>

<template>
  <div class="flex flex-col gap-3">
    <el-input
      ref="inputRef"
      v-model="query"
      placeholder="搜索合约代码..."
      clearable
      autofocus
      @keydown.enter.prevent="onInputEnter"
    />

    <div class="relative h-80 overflow-auto">
      <div
        v-if="loading"
        class="absolute inset-0 z-10 flex items-center justify-center bg-white/60 text-lg text-gray-500"
      >
        玩命加载中...
      </div>

      <template v-if="!loading">
        <div
          v-if="results.length > 0"
          :ref="setContainerRef"
          class="grid grid-cols-2 gap-2 p-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5"
          role="listbox"
          @keydown="onListKeydown"
        >
          <div
            v-for="(item, index) in results"
            :key="item.vt_symbol || item.symbol"
            :ref="el => setItemRef(el as unknown as HTMLElement, index)"
            class="hover:ring-primary focus:ring-primary cursor-pointer rounded border border-gray-200 p-2 outline-none hover:ring-1 focus:ring-1"
            tabindex="-1"
            @click="handleSelect(item)"
          >
            <div class="flex items-center gap-1 font-mono">
              <span>{{ item.symbol }}</span>
              <component
                :is="MDominantIcon"
                v-if="item.is_dominant"
                class="text-red-500"
              />
            </div>
            <div
              v-if="props.showDetails"
              class="mt-0.5 text-[10px] text-gray-500"
            >
              <span v-if="item.exchange"> {{ item.exchange }}</span>
            </div>
          </div>
        </div>
        <div v-else class="flex h-full items-center justify-center">
          <el-empty description="暂无搜索结果" />
        </div>
      </template>
    </div>
  </div>
</template>
